package com.kid.modules.utils.pvg;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.kid.modules.utils.DomainConst;
import com.kid.modules.utils.ThreadLocalUtils;
import com.kid.mybatis.domain.AccRoleExample;
import com.kid.mybatis.domain.AccRoleKey;
import com.kid.mybatis.domain.Pvg;
import com.kid.mybatis.domain.PvgExample;
import com.kid.mybatis.domain.PvgExample.Criteria;
import com.kid.mybatis.mapper.AccRoleMapper;
import com.kid.mybatis.mapper.PvgMapper;

public class PvgCheckServiceImpl implements PvgCheckService {

	@Autowired
	private PvgMapper pvgMapper;

	@Autowired
	private AccRoleMapper accRoleMapper;

	@Override
	public boolean hasPvg(int pvgItem) {
		return this.hasPvg(pvgItem, ThreadLocalUtils.getAccInfo().getId());
	}

	@Override
	public boolean hasPvg(int pvgItem, int userId) {
		PvgExample example = new PvgExample();
		example.createCriteria().andResidEqualTo(userId)
				.andItemidEqualTo(pvgItem);
		return pvgMapper.selectByExample(example).size() > 0;
	}

	@Override
	public List<Pvg> getPvg() {
		return this.getPvg(ThreadLocalUtils.getAccInfo().getId());
	}

	@Override
	public List<Pvg> getPvg(int userId) {
		List<Integer> roldeIds = new ArrayList<Integer>();
		AccRoleExample arExample = new AccRoleExample();
		arExample.createCriteria().andAccidEqualTo(userId);
		List<AccRoleKey> arks = this.accRoleMapper.selectByExample(arExample);
		for (AccRoleKey ark : arks) {
			roldeIds.add(ark.getRoleid());
		}
		PvgExample example = new PvgExample();
		Criteria criteria = example.createCriteria();
		criteria.andRestypeEqualTo(DomainConst.Pvg_RoleType).andResidIn(
				roldeIds);
		example.or().andRestypeEqualTo(DomainConst.Pvg_AccType)
				.andResidEqualTo(userId);
		return pvgMapper.selectByExample(example);
	}

	@Override
	public List<Pvg> getPvgFiltered() {
		return this.getPvgFiltered(ThreadLocalUtils.getAccInfo().getId());
	}

	@Override
	public List<Pvg> getPvgFiltered(int userId) {
		List<Pvg> pvgs = this.getPvg(userId);
		List<Integer> uuKeys = new ArrayList<Integer>();
		List<Pvg> rePvgs = new ArrayList<Pvg>();
		for (Pvg pvg : pvgs) {
			if (!uuKeys.contains(pvg.getItemid())) {
				rePvgs.add(pvg);
			}
		}
		return rePvgs;
	}

}
